import {
  designWidth,
  deviceRatio,
  unitPrecision,
  uniWidth,
} from "./common/app.config";

/*export function transformPxToRpx(px: string | number): string {
  // 公式：rpx = px * (750 / 设计稿宽度)
  px = parseFloat(px as string);
  const rpx = px * (uniWidth / designWidth);
  return rpx.toFixed(unitPrecision) + "rpx";
}*/
export function transformPxToRpx(px: string | number): string {
  const rpx = (parseInt(px.toString()) * deviceRatio * uniWidth) / designWidth;
  return `${rpx.toFixed(unitPrecision)}rpx`;
}
export function transformRpxToPx(rpx: string | number): string {
  // 公式：px = (rpx * 设计稿宽度) / 750
  rpx = parseFloat(rpx as string);
  return uni.upx2px(rpx) + "px";
}

export const pxChangeRem = (px: number | string) => {
  px = parseFloat(px as string);
  const value =
    Math.round((px / designWidth) * 10 ** unitPrecision) / 10 ** unitPrecision;
  return value + "rem";
};

export function _css(el: any, key: any, value?: any) {
  const reg = /^-?\d+.?\d*(px|pt|em|rem|vw|vh|%|rpx|ms)$/i;
  if (value === undefined) {
    let val = null;
    if ("getComputedStyle" in window) {
      val = window.getComputedStyle(el, null)[key];
    } else {
      val = el.currentStyle[key];
    }
    return reg.test(val) ? parseFloat(val) : val;
    // return parseFloat(val)
  } else {
    if (
      [
        "top",
        "left",
        "bottom",
        "right",
        "width",
        "height",
        "font-size",
        "margin",
        "padding",
      ].includes(key)
    ) {
      if (!reg.test(value)) {
        if (!String(value).includes("calc")) {
          value += "px";
        }
      }
    }
    // console.log(value)
    if (key === "transform") {
      //直接设置不生效
      el.style.webkitTransform =
        el.style.MsTransform =
        el.style.msTransform =
        el.style.MozTransform =
        el.style.OTransform =
        el.style.transform =
          value;
    } else {
      el.style[key] = value;
    }
  }
}
export const getImg = (str: string) => {
  return new URL(`../static/img/${str}`, import.meta.url).href;
};
export const getSvg = (str: string) => {
  return new URL(`../static/svg/${str}.svg`, import.meta.url).href;
};
export const getIcon = (str: any) => {
  return new URL(`../static/icons/${str}`, import.meta.url).href;
};
